from typing import Any, Awaitable, Callable, Dict, Union

from aiogram import BaseMiddleware
from aiogram.types import CallbackQuery, Message, Update
from fluentogram import TranslatorRunner

from app.bot.services.locale import Localizator
from app.database.services.users import get_user_language


class LocaleMiddleware(BaseMiddleware):
    def __init__(self, localizator: Localizator):
        self._loc: Localizator = localizator

    async def __call__(
        self,
        handler: Callable[[Update, Dict[str, Any]], Awaitable[Any]],
        event: Union[Update, Message, CallbackQuery],
        data: Dict[str, Any],
    ) -> Any:

        user_lang = await get_user_language(data["db_session"], event.from_user.id)

        if user_lang == "" or user_lang is None:
            user_lang = event.from_user.language_code

        _locale: TranslatorRunner = self._loc.get_by_locale(user_lang)

        data["locale"] = _locale

        return await handler(event, data)
